package com.ncmem.up7.biz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.ncmem.up7.sql.SqlExec;
import com.ncmem.up7.sql.SqlParam;
import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class DbFolder {

    //根节点
    JSONObject root ;//= new JObject { { "f_id", "" }, { "f_nameLoc", "根目录" }, { "f_pid", "" }, { "f_pidRoot", "" },{ "f_pathRel",""} };

    public DbFolder() {
        this.root = new JSONObject();
        this.root.put("f_id", "");
        this.root.put("f_nameLoc", "根目录");
        this.root.put("f_pid", "");
        this.root.put("f_pidRoot", "");
        this.root.put("f_pathRel", "");
    }

    public Map<String, JSONObject> toDic(JSONArray folders)
    {
        Map<String, JSONObject> dt = new HashMap<String, JSONObject>();
        for(int i = 0 , l = folders.size();i<l;++i)
        {
            JSONObject o = folders.getJSONObject(i);
            String id = o.getString("f_id");
            dt.put(id, o);
        }
        return dt;
    }

    /// <summary>
    /// 构建路径
    /// </summary>
    /// <param name="fd"></param>
    /// <returns></returns>
    public JSONArray build_path(JSONObject fdCur)
    {
        //查询文件表目录数据
        SqlExec se = new SqlExec();
        JSONArray files = se.select("up7_files", "f_id,f_pid,f_nameLoc,f_pathRel",
                new SqlParam[] { new SqlParam("f_fdTask", true) },
                "");
        JSONArray folders = se.select("up7_folders",
                "f_id,f_pid,f_nameLoc,f_pathRel",
                new SqlParam[] { },
                "");
        String id = fdCur.getString("f_id").trim();

        //根目录
        ArrayList<JSONObject> psort = new ArrayList<JSONObject>();
        if (StringUtils.isBlank(id) )
        {
            psort.add(0, this.root);

            return JSONArray.fromObject(psort);
        }

        //构建目录映射表(id,folder)
        Map<String, JSONObject> dtFiles = this.toDic(files);
        Map<String, JSONObject> dtFolders = this.toDic(folders);

        for(String key : dtFolders.keySet())
        {
            if(!dtFiles.containsKey(key)) dtFiles.put(key, dtFolders.get(key));
        }

        //按层级顺序排列目录
        psort = this.sortByPid(dtFiles, id, psort);

        psort.add(0, this.root);

        return JSONArray.fromObject(psort);
    }

    public ArrayList<JSONObject> sortByPid(Map<String, JSONObject> dt, String idCur, ArrayList<JSONObject> psort)
    {
        String cur = idCur;
        while (true)
        {
            //key不存在
            if ( !dt.containsKey(cur) ) break;

            JSONObject d = dt.get(cur);//查父ID
            psort.add(0, d);//将父节点排在前面
            cur = d.getString("f_pid").trim();//取父级ID

            if (cur.trim() == "0") break;
            if (StringUtils.isBlank(cur)) break;
        }
        return psort;
    }


    public static boolean existSameFolder(String name,String pid)
    {
        SqlExec se = new SqlExec();

        //子目录
        if(StringUtils.isEmpty(pid))
        {
            return se.count("up7_folders",new SqlParam[] {
                    new SqlParam("f_nameLoc",name),
                    new SqlParam("f_pid",pid),
                    new SqlParam("f_deleted",false)
            })>0;
        }//根目录
        else
        {
            return se.count("up7_files",new SqlParam[] {
                    new SqlParam("f_nameLoc",name),
                    new SqlParam("f_pid",pid),
                    new SqlParam("f_deleted",false)
            })>0;
        }
    }


    public static String getPathRel(String id)
    {
        SqlExec se = new SqlExec();
        JSONObject ret = se.read("up7_files", "f_pathRel", new SqlParam[] { new SqlParam("f_id", id) });
        if( !ret.has("f_pathRel") )
            ret = se.read("up7_folders", "f_pathRel", new SqlParam[] { new SqlParam("f_id", id) });
        return ret.getString("f_pathRel");
    }

    /**
     * 更新子文件路径
     * @param pathRelOld
     * @param pathRelNew
     */
    public void updatePathRel(String pathRelOld,String pathRelNew)
    {
        //更新子文件路径
        String sql = String.format("update up7_folders set f_pathRel=REPLACE(f_pathRel,'%s/','%s/') where CHARINDEX('%s/',f_pathRel)>0",
                pathRelOld,
                pathRelNew,
                pathRelOld
        );

        SqlExec se = new SqlExec();
        se.exec(sql);
    }
}
